package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.domain.Category;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    //菜品
    @Autowired
    private DishService dishService;

    //菜品口味
    @Autowired
    private DishFlavorService dishFlavorService;

    //菜品分页查询获得菜品分类需要使用到
    @Autowired
    private CategoryService categoryService;


    /**
     * 添加新菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){

        log.info("dishDto参数：{}",dishDto);

        //调用自定义方法
        dishService.saveWithFlavor(dishDto);


        return R.success("新增菜品成功！");
        //return  null;
    }



    /**
     * 菜品分页条件查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        //构造分页构造器
        Page<Dish> pageInfo = new Page<Dish>(page,pageSize);

        Page<DishDto> dishDtoPage = new Page<DishDto>();

        //构建条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加具体条件
        queryWrapper.like(name != null, Dish::getName, name);
        //构造排序条件  修改时间降序排
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //调用方法
        dishService.page(pageInfo, queryWrapper);


        //对象拷贝  records单独处理
        BeanUtils.copyProperties(pageInfo, dishDtoPage, " records ");

        List<Dish> records = pageInfo.getRecords();  //Dish对象集合
        //Dish  转为  DishDto
        List<DishDto> list = records.stream().map(item -> {   //item表示集合中每一个dish

            DishDto dishDto = new DishDto();              //空对象
            BeanUtils.copyProperties(item, dishDto);      //对象拷贝

            Long categoryId = item.getCategoryId();       //分类id
            Category category = categoryService.getById(categoryId); //根据id查询分类对象

            if(category !=null ){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);    //设置名称
            }

            return dishDto;

        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list); //DishDto对象集合
        return R.success(dishDtoPage);
    }

    /**
     * 根据id查询  回显数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){

        log.info("id:{}",id);

        //
        DishDto dishDto = dishService.getByIdWithFlavor(id);

        return  R.success(dishDto);

    }


    /*
     *修改数据
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> updateById(@RequestBody DishDto dishDto){

        dishService.updateWithFlavor(dishDto);

        return R.success("菜品修改成功！");
    }

    /**
     * 根据id删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(@RequestParam List<Long> ids){
         log.info("ids数据:{}",ids);

        //调用自定义方法
        dishService.deleteByIds(ids);

        return R.success("菜品删除成功");
    }


    /**
     * 批量起售 或 停售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateSta(@PathVariable int status,Long[] ids){
        //
        //调用自定义方法
        dishService.updateStatus(status,ids);
        return R.success("修改成功");
    }


    /**
     * 根据菜品表Dish中 category_id、 status = 1查询对应的菜品数据
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){


        //构造条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //过滤条件
        queryWrapper.eq(StringUtils.isNotEmpty(String.valueOf(dish.getCategoryId())),Dish::getCategoryId,dish.getCategoryId());

        //添加条件 查询状态为 1 (起售状态) 的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //排序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //SQL: select * from dish where category_id = ? and status =1
        List<Dish> list = dishService.list(queryWrapper);
        //return R.success(list);

        List<DishDto> dishDtos = list.stream().map(item -> {
            DishDto dishDto = new DishDto();         //创建空对象
            BeanUtils.copyProperties(item, dishDto);  //对象拷贝

            Long categoryId = item.getCategoryId();  // 获取分类cotegory_id
            Category category = categoryService.getById(categoryId); //根据cotegory_id查询到分类对象
            if (category != null) {                   // 健壮性判断  分类对象不为空
                String name = category.getName();   // 获取分类名称
                dishDto.setCategoryName(name);      // 将名称设置到 categoryName属性上
            }

            Long id = item.getId();  // 获取当前菜品id  菜品表dish
            // 构建条件构造器
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, id);                              //dish_id  = id

            // SQL:select * from dish_flavor  where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);  //当前菜品id查询所有口味
            dishDto.setFlavors(dishFlavorList);  // 将该口味设置到 flavor属性上

            return dishDto;

        }).collect(Collectors.toList());

        return  R.success(dishDtos);
    }

}
